#!/usr/bin/env bash

help(){
    cat<<__EOF__
Usage: m volume [OPTIONS] [ARGUMENTS]

Description: Manage the system volume on macOS from the command line

Options:
  --help         Show this help message and exit
  --set LEVEL    Set the volume to LEVEL (0-100),
  --mute         Mute the system volume
  --unmute       Unmute the system volume

Examples:
  m volume --set 70     # set the volume to 70%
  m volume              # get the volume level and if muted or not
  m volume --unmute     # unmute
__EOF__
}

vol_status(){
    local value=$(osascript -e 'output muted of (get volume settings)')
    local level=$(osascript -e "output volume of (get volume settings)")
    if [[ "$value" == "true" ]]; then
        echo "Vol: $level [Muted]"
    else
        echo "Vol: $level [Unmuted]"
    fi
}

mute(){
    osascript -e "set volume output muted true"
    echo "Vol: Muted"
}

unmute(){
    osascript -e "set volume output muted false"
    echo "Vol: Unmuted"

}

set_vol(){
    case "${1}" in
        [0-9]*)
        ;;
        *)
            echo "Invalid volume level: '${1}'" >&2
            exit 1
    esac
    # osascript -e "set volume output volume (get output volume of (get volume settings) $1)"
    osascript -e "set volume output volume ${1}"
    vol_status
}

case $1 in
    --help)
        help
        ;;
    --set)
        set_vol "${2}"
        ;;
    --mute)
        mute
        ;;
    --unmute)
        unmute
        ;;
    *)
        vol_status
        ;;
esac
